# coding=utf-8
import json
import logging
import os
import yaml
from genson import SchemaBuilder
from jsonschema.validators import validate



# 获取项目根目录
projectname = 'hgws'
path = os.path.split(os.path.realpath(__file__))[0]

if path.endswith(projectname):
    pass
else:
    idx = path.find(projectname)
    path = path[:idx + len(projectname)]


class Utils:

    # 读取yaml数据
    @classmethod
    def get_data_yaml(self, path):
        """读取yaml数据"""
        with open(path, "r", encoding="utf-8") as file:
            data = yaml.safe_load(file)
        return data


    @classmethod
    def generate_jsonschema(cls,obj):
        """
        生成jsonschma
        SchemaBuilder 类似于一个工厂类，用于构建 JSON Schema。
        builder.add_object(obj) 方法会分析传入的对象 obj 并基于其属性来创建一个 JSON Schema 的草稿。
        builder.to_schema() 将构建的结果转换成一个有效的 JSON Schema 对象或字典
        :param obj:
        :return:
        """
        builder = SchemaBuilder()
        builder.add_object(obj)
        return builder.to_schema()

    @classmethod
    def validate_jsonschema(cls,data_obj,schema):
        """
        通过jsonschema断言
        :param data_obj:待验证的数据对象
        :param schema: 用于验证的jsonschema
        :return:
        """
        try:
            validate(data_obj,schema=schema)
            return True
        except Exception as e:
            logging.info(f"jsonschema断言失败，{e}")
            return False

    @classmethod
    def generate_jsonschema_by_file(cls, obj, file_path):
        """
        将生成的 jsonschema 数据保存到json文件中
        :param obj:
        :param file_path:
        :return:
        """
        jsonschema_data = cls.generate_jsonschema(obj)
        with open(file_path, "w") as f:
            json.dump(jsonschema_data, f)

    @classmethod
    def validate_jsonschema_by_file(cls, obj, file_path):
        """
        读取json文件用于验证的jsonschema，和实际接口返回的内容对比
        :param obj:
        :param file_path:
        :return:
        """
        with open(file_path, "r") as f:
            schema_data = json.load(f)
        return cls.validate_jsonschema(obj, schema_data)

